<template>
  <div class="order-rating-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>评价服务</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 订单信息 -->
      <el-card class="order-info-card" v-loading="loading">
        <div v-if="orderInfo" class="order-summary">
          <div class="service-info">
            <div class="service-image">
              <el-image
                :src="orderInfo.service?.image || '/default-service.jpg'"
                fit="cover"
                class="image"
              />
            </div>
            <div class="service-details">
              <h3>{{ orderInfo.service?.name }}</h3>
              <p class="merchant-name">{{ orderInfo.merchant?.name }}</p>
              <div class="order-meta">
                <span>订单号：{{ orderInfo.orderNumber }}</span>
                <span>完成时间：{{ formatDate(orderInfo.completedAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 评价表单 -->
      <el-form 
        :model="ratingForm" 
        :rules="ratingRules" 
        ref="formRef" 
        label-width="100px"
        class="rating-form"
      >
        <!-- 服务评分 -->
        <el-card class="rating-section">
          <template #header>
            <h3>服务评分</h3>
          </template>

          <el-form-item label="总体评分" prop="overallRating" required>
            <div class="rating-container">
              <el-rate 
                v-model="ratingForm.overallRating" 
                :max="5" 
                allow-half 
                size="large"
                :colors="ratingColors"
                show-text
              />
              <span class="rating-desc">{{ getRatingDesc(ratingForm.overallRating) }}</span>
            </div>
          </el-form-item>

          <!-- 详细评分 -->
          <div class="detailed-ratings">
            <el-form-item label="服务态度" prop="serviceAttitude">
              <el-rate 
                v-model="ratingForm.serviceAttitude" 
                :max="5" 
                allow-half
                :colors="ratingColors"
              />
            </el-form-item>

            <el-form-item label="服务质量" prop="serviceQuality">
              <el-rate 
                v-model="ratingForm.serviceQuality" 
                :max="5" 
                allow-half
                :colors="ratingColors"
              />
            </el-form-item>

            <el-form-item label="服务效率" prop="serviceEfficiency">
              <el-rate 
                v-model="ratingForm.serviceEfficiency" 
                :max="5" 
                allow-half
                :colors="ratingColors"
              />
            </el-form-item>

            <el-form-item label="价格合理" prop="priceValue">
              <el-rate 
                v-model="ratingForm.priceValue" 
                :max="5" 
                allow-half
                :colors="ratingColors"
              />
            </el-form-item>
          </div>
        </el-card>

        <!-- 服务标签 -->
        <el-card class="tags-section">
          <template #header>
            <h3>服务标签</h3>
          </template>

          <el-form-item>
            <div class="rating-tags">
              <el-check-tag
                v-for="tag in availableTags"
                :key="tag"
                :checked="ratingForm.tags.includes(tag)"
                @change="toggleTag(tag)"
                class="rating-tag"
              >
                {{ tag }}
              </el-check-tag>
            </div>
          </el-form-item>
        </el-card>

        <!-- 文字评价 -->
        <el-card class="comment-section">
          <template #header>
            <h3>文字评价</h3>
          </template>

          <el-form-item prop="comment">
            <el-input
              v-model="ratingForm.comment"
              type="textarea"
              :rows="5"
              placeholder="请分享您的服务体验，您的评价对其他用户很有帮助"
              maxlength="500"
              show-word-limit
              resize="none"
            />
          </el-form-item>
        </el-card>

        <!-- 图片上传 -->
        <el-card class="upload-section">
          <template #header>
            <h3>上传图片</h3>
          </template>

          <el-form-item>
            <el-upload
              v-model:file-list="ratingForm.images"
              :action="uploadAction"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :limit="6"
              multiple
              accept="image/*"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  最多上传6张图片，支持jpg、png格式，单张不超过5MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-card>

        <!-- 是否匿名 -->
        <el-card class="anonymous-section">
          <el-form-item>
            <el-checkbox v-model="ratingForm.isAnonymous">
              匿名评价
            </el-checkbox>
            <div class="anonymous-tip">
              选择匿名评价后，您的用户名将不会在评价中显示
            </div>
          </el-form-item>
        </el-card>
      </el-form>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <el-button
          type="primary"
          size="large"
          :loading="submitting"
          @click="handleSubmit"
          class="submit-btn"
          :disabled="!isFormValid"
        >
          提交评价
        </el-button>
      </div>
    </div>

    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible" title="图片预览">
      <img :src="dialogImageUrl" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { orderApi } from '@/services/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 数据定义
const formRef = ref()
const loading = ref(true)
const submitting = ref(false)
const orderInfo = ref(null)
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 上传配置
const uploadAction = ref('/api/upload/image')

// 评分颜色
const ratingColors = ['#F56C6C', '#E6A23C', '#5CB87A']

// 可用标签
const availableTags = [
  '服务及时', '态度友好', '技术专业', '价格实惠',
  '环境干净', '效果满意', '值得推荐', '还会再来',
  '准时到达', '工具齐全', '清洁彻底', '服务细致'
]

// 评价表单
const ratingForm = reactive({
  overallRating: 5,
  serviceAttitude: 5,
  serviceQuality: 5,
  serviceEfficiency: 5,
  priceValue: 5,
  tags: [],
  comment: '',
  images: [],
  isAnonymous: false
})

// 表单验证规则
const ratingRules = {
  overallRating: [
    { required: true, message: '请给出总体评分', trigger: 'change' }
  ],
  serviceAttitude: [
    { required: true, message: '请评价服务态度', trigger: 'change' }
  ],
  serviceQuality: [
    { required: true, message: '请评价服务质量', trigger: 'change' }
  ],
  serviceEfficiency: [
    { required: true, message: '请评价服务效率', trigger: 'change' }
  ],
  priceValue: [
    { required: true, message: '请评价价格合理性', trigger: 'change' }
  ]
}

// 计算属性
const isFormValid = computed(() => {
  return ratingForm.overallRating > 0 && 
         ratingForm.serviceAttitude > 0 && 
         ratingForm.serviceQuality > 0 && 
         ratingForm.serviceEfficiency > 0 && 
         ratingForm.priceValue > 0
})

// 生命周期
onMounted(() => {
  const orderId = route.params.id
  if (orderId) {
    fetchOrderInfo(orderId)
  }
})

// 方法定义
const fetchOrderInfo = async (orderId) => {
  try {
    loading.value = true
    const response = await orderApi.getOrderDetail(orderId)
    orderInfo.value = response.data
  } catch (error) {
    console.error('获取订单信息失败:', error)
    
    // 使用模拟数据
    const mockOrderId = parseInt(orderId)
    orderInfo.value = {
      id: mockOrderId,
      orderNumber: `202412280${mockOrderId.toString().padStart(3, '0')}`,
      status: 'completed',
      completedAt: new Date(Date.now() - 3600000),
      merchant: {
        id: 1,
        name: '专业洗护店'
      },
      service: {
        id: 1,
        name: '高档衣物干洗',
        image: '/default-service.jpg'
      }
    }
    
    ElMessage.error('获取订单信息失败，显示模拟数据')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  router.back()
}

const toggleTag = (tag) => {
  const index = ratingForm.tags.indexOf(tag)
  if (index > -1) {
    ratingForm.tags.splice(index, 1)
  } else {
    ratingForm.tags.push(tag)
  }
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = (file, fileList) => {
  ratingForm.images = fileList
}

const handleUploadSuccess = (response, file, fileList) => {
  ratingForm.images = fileList
  ElMessage.success('图片上传成功')
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    await ElMessageBox.confirm(
      '确定要提交评价吗？提交后无法修改。',
      '提交评价',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '再想想',
        type: 'info'
      }
    )

    submitting.value = true
    
    const ratingData = {
      orderId: orderInfo.value.id,
      overallRating: ratingForm.overallRating,
      serviceAttitude: ratingForm.serviceAttitude,
      serviceQuality: ratingForm.serviceQuality,
      serviceEfficiency: ratingForm.serviceEfficiency,
      priceValue: ratingForm.priceValue,
      tags: ratingForm.tags,
      comment: ratingForm.comment,
      images: ratingForm.images.map(img => img.url || img.response?.url).filter(Boolean),
      isAnonymous: ratingForm.isAnonymous
    }
    
    await orderApi.submitRating(ratingData)
    
    ElMessage.success('评价提交成功！感谢您的反馈')
    
    // 延迟跳转到订单详情页
    setTimeout(() => {
      router.push(`/orders/${orderInfo.value.id}`)
    }, 1500)
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交评价失败:', error)
      ElMessage.error('提交评价失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

const getRatingDesc = (rating) => {
  if (rating >= 4.5) return '非常满意'
  if (rating >= 3.5) return '满意'
  if (rating >= 2.5) return '一般'
  if (rating >= 1.5) return '不满意'
  if (rating >= 0.5) return '非常不满意'
  return '请评分'
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.order-rating-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .el-card__header {
    padding: 16px 20px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .el-card__body {
    padding: 20px;
  }
}

.order-info-card {
  .order-summary {
    .service-info {
      display: flex;
      gap: 12px;

      .service-image {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        overflow: hidden;
        flex-shrink: 0;

        .image {
          width: 100%;
          height: 100%;
        }
      }

      .service-details {
        flex: 1;

        h3 {
          margin: 0 0 4px 0;
          font-size: 16px;
          color: #333;
        }

        .merchant-name {
          margin: 0 0 8px 0;
          color: #666;
          font-size: 14px;
        }

        .order-meta {
          display: flex;
          flex-direction: column;
          gap: 4px;
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

.rating-form {
  .el-form-item {
    margin-bottom: 20px;
  }

  .el-form-item__label {
    font-weight: 500;
    color: #333;
  }
}

.rating-section {
  .rating-container {
    display: flex;
    align-items: center;
    gap: 16px;

    .rating-desc {
      font-size: 16px;
      font-weight: 500;
      color: #409eff;
    }
  }

  .detailed-ratings {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid #f0f0f0;

    .el-form-item {
      margin-bottom: 16px;
    }
  }
}

.tags-section {
  .rating-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .rating-tag {
      margin: 0;
    }
  }
}

.upload-section {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s ease;

    &:hover {
      border-color: #409eff;
    }
  }

  :deep(.el-upload-list--picture-card) {
    .el-upload-list__item {
      width: 100px;
      height: 100px;
      margin: 0 8px 8px 0;
    }
  }

  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 98px;
  }
}

.anonymous-section {
  .anonymous-tip {
    margin-top: 8px;
    color: #999;
    font-size: 12px;
    line-height: 1.4;
  }
}

.submit-section {
  margin-top: 24px;
  margin-bottom: 40px;

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 500;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .order-info-card .service-info {
    flex-direction: column;
    text-align: center;

    .service-image {
      align-self: center;
    }

    .service-details .order-meta {
      align-items: center;
    }
  }

  .rating-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;

    .rating-desc {
      font-size: 14px;
    }
  }

  .rating-tags {
    gap: 6px;

    .rating-tag {
      font-size: 12px;
      padding: 4px 8px;
    }
  }

  .upload-section {
    :deep(.el-upload-list--picture-card) {
      .el-upload-list__item {
        width: 80px;
        height: 80px;
      }
    }

    :deep(.el-upload--picture-card) {
      width: 80px;
      height: 80px;
    }
  }
}
</style> 